package com.basker.pisces.utils;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * 数字工具类
 *
 * @author hangwen
 */
public class NumberUtils {
    private static final Logger logger = LoggerFactory.getLogger(NumberUtils.class);

    public static boolean isNumberClass(Class<?> cls) {
        if (cls == int.class || cls == long.class || cls == short.class || cls == byte.class || cls == float.class
                || cls == double.class) {
            return true;
        }

        return Number.class.isAssignableFrom(cls);
    }

    public static <T extends Number> T parse(Object val, Class<T> numberClass) {
        Assert.notNull(numberClass, "parameter 'numberClass' is required");

        if (val == null || val.equals("")) {
            return null;
        }

        if (val instanceof Number) {
            return org.springframework.util.NumberUtils.convertNumberToTargetClass((Number) val, numberClass);
        }

        if (val.getClass().isEnum() && numberClass.equals(Integer.class)) {
            @SuppressWarnings("unchecked")
            T ret = (T) Integer.valueOf(((Enum<?>) val).ordinal());
            return ret;
        }

        if (val instanceof Date && numberClass.equals(Long.class)) {
            @SuppressWarnings("unchecked")
            T ret = (T) Long.valueOf(((Date) val).getTime());
            return ret;
        }

        return org.springframework.util.NumberUtils.parseNumber(val.toString(), numberClass);
    }

    public static Integer parseInt(Object val) {
        return parse(val, Integer.class);
    }

    public static Long parseLong(Object val) {
        return parse(val, Long.class);
    }

    public static <T extends Number> T tryParse(Object val, Class<T> numberClass) {
        try {
            return parse(val, numberClass);
        } catch (IllegalArgumentException ex) {
            if (logger.isWarnEnabled() && numberClass != null) {
                logger.warn(val + " can not parse to number class:" + numberClass.getSimpleName() + "!");
            }
            return null;
        }
    }
}
